// 认证相关工具函数
import axios from 'axios'

// 保存用户信息
export const saveUserInfo = (userInfo) => {
  localStorage.setItem('userInfo', JSON.stringify(userInfo))
}

// 获取用户信息
export const getUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  try {
    return userInfoStr ? JSON.parse(userInfoStr) : null
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return null
  }
}

// 保存token
export const saveToken = (token) => {
  localStorage.setItem('token', token)
  // 设置axios请求头
  axios.defaults.headers.common['token'] = token
}

// 获取token
export const getToken = () => {
  return localStorage.getItem('token')
}

// 退出登录
export const logout = () => {
  localStorage.removeItem('userInfo')
  localStorage.removeItem('token')
  // 清除axios请求头
  delete axios.defaults.headers.common['token']
}

// 检查是否已登录
export const isLoggedIn = () => {
  return !!getToken()
}

// 初始化认证信息
export const initAuth = () => {
  const token = getToken()
  if (token) {
    axios.defaults.headers.common['token'] = token
  }
}